package seatiger.tomcat.catalina.logger;

import seatiger.tomcat.catalina.Container;
import seatiger.tomcat.catalina.LifecycleException;
import seatiger.tomcat.catalina.Logger;

import javax.servlet.ServletException;
import java.io.CharArrayWriter;
import java.io.PrintWriter;

/**
 * logger的基础实现
 */
public abstract class LoggerBase implements Logger {
    private Container container;
    private int debug = 0;
    protected static final String info = "seatiger.tomcat.catalina.logger.LoggerBase/1.0";

    /**
     * 默认级别是debug级别
     */
    private int verbosity = debug;

    @Override
    public Container getContainer() {
        return container;
    }

    @Override
    public void setContainer(Container container) {
        this.container = container;
    }

    @Override
    public String getInfo() {
        return info;
    }

    @Override
    public int getVerbosity() {
        return this.verbosity = verbosity;
    }

    @Override
    public void setVerbosity(int verbosity) {
        this.verbosity = verbosity;
    }

    @Override
    public abstract void log(String message);

    @Override
    public void log(Exception exception, String msg) {
        log(msg, exception);
    }

    @Override
    public void log(String message, Throwable throwable) {
        CharArrayWriter buf = new CharArrayWriter();
        PrintWriter writer = new PrintWriter(buf);
        writer.println(message);
        throwable.printStackTrace(writer);
        Throwable rootCause = null;
        if (throwable instanceof LifecycleException){
            rootCause = ((LifecycleException) throwable).getThrowable();
        }else if(throwable instanceof ServletException){
            rootCause = ((ServletException) throwable).getRootCause();
        }

        if (rootCause != null){
            writer.println("----- Root Cause -----");
            rootCause.printStackTrace(writer);
        }
        log(buf.toString());
    }

    @Override
    public void log(String message, int verbosity) {
        if (this.verbosity >= verbosity){
            log(message);
        }
    }

    @Override
    public void log(String message, Throwable throwable, int verbosity) {
        if (this.verbosity >= verbosity){
            log(message,throwable);
        }
    }

    public void setVerbosityLevel(String verbosity){
        verbosity = verbosity.toUpperCase();
        switch (verbosity){
            case FATAL_STR: this.verbosity =FATAL; break;
            case ERROR_STR: this.verbosity = ERROR; break;
            case WARNING_STR: this.verbosity = WARNING; break;
            case INFORMATION_STR: this.verbosity = INFORMATION; break;
            case DEBUG_STR: this.verbosity = DEBUG; break;
        }

    }
}
